package com.hongdee.crm.sale.service.impl;

import com.hongdee.common.dao.IHibernateDao;
import com.hongdee.common.dao.IImpHibernateDao;
import com.hongdee.common.dao.IImpJdbcDao;
import com.hongdee.common.dao.IJdbcDao;
import com.hongdee.common.util.DateUtils;
import com.hongdee.common.util.StringUtil;
import com.hongdee.common.util.TokenUtil;
import com.hongdee.crm.sale.dao.ITCrmCarSaleDao;
import com.hongdee.crm.sale.entity.TCrmCarSale;
import com.hongdee.crm.sale.service.ITCrmCarSaleService;
import com.hongdee.crm.task.service.ITCrmTimeTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 名  称:TCrmCarSaleServiceImpl
 * 类  型: class
 * 描  述:
 * 路  径:
 * 作  者: 术洪超
 * 日  期:2017-02-22 17:18
 */
@Service
public class TCrmCarSaleServiceImpl implements ITCrmCarSaleService {

    private String tabName = "T_CRM_CAR_SALE";
    @Autowired
    private ITCrmCarSaleDao itCrmCarSaleDao;

    @Autowired
    private IImpJdbcDao iImpJdbcDao;

    @Autowired
    private IImpHibernateDao iImpHibernateDao;

    @Autowired
    private IHibernateDao iHibernateDao;

    @Autowired
    private IJdbcDao iJdbcDao;

    @Autowired
    private ITCrmTimeTaskService itCrmTimeTaskService;

    /**
     * @param uid   登录用户ID
     * @param start 分页开始页
     * @param limit 每页显示条数
     * @return
     * @throws Exception
     * @desc 导入确认前分页
     * @author 术洪超
     */

    @Override
    public Map impPage(String uid, String start, String limit) throws Exception {
        StringBuffer sqlBuffer = new StringBuffer();
        sqlBuffer.append("select * from " + tabName + " where 1=1 ");
        String oId = TokenUtil.getCompanyId(uid);
        List params = new ArrayList();
        if (!StringUtils.isEmpty(oId)) {
            sqlBuffer.append(" and company_id = ? ");
            params.add(oId);
        }

        return iImpJdbcDao.queryForPageMap(start, limit, sqlBuffer.toString(), params.toArray());
    }

    /**
     * @param id 确认后要删除数据的主键
     * @return
     * @throws Exception
     * @desc 导入确认后删除导入表数据
     * @author 术洪超
     */
    @Override
    public void impDel(String id) throws Exception {
        String hql = "delete from TCrmCarSale where id =:id ";
        Map params = new HashMap();
        params.put("id", id);
        this.iImpHibernateDao.executeHqlWithParams(hql, params);
    }


    /**
     * @return
     * @throws Exception
     * @desc 单条导入确认
     * @author 术洪超
     */

    @Override
    public void impConfirm(String id, String uid) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);
        String sql1 = "select * from " + tabName + " where vin = ? and company_id = ? limit 1";
        Map existData;
        TCrmCarSale crmCarSale;
        crmCarSale = (TCrmCarSale) this.iImpHibernateDao.findEntity(TCrmCarSale.class, id);
        existData = this.iJdbcDao.queryForMapBySqlWithParams(sql1, crmCarSale.getVin(), crmCarSale.getCompanyId());
        //判断数据是否已存在
        if (existData.size() == 0) {
            //新数据
            crmCarSale.setId(null);
            crmCarSale.setCreateTime(System.currentTimeMillis());
            crmCarSale.setUpdateTime(System.currentTimeMillis());
            crmCarSale.setConfirmer(uid);
            crmCarSale.setConfirmDate(System.currentTimeMillis());
        } else {
            //已有数据
            crmCarSale.setId(existData.get("id").toString());
            crmCarSale.setUpdateTime(System.currentTimeMillis());
            crmCarSale.setConfirmer(uid);
            crmCarSale.setConfirmDate(System.currentTimeMillis());
        }
        this.iHibernateDao.saveOrUpdateEntity(crmCarSale);
        //保存或更新
        this.impDel(id);

        this.itCrmTimeTaskService.updFromCompanyQuartz();
        this.itCrmTimeTaskService.createCrmCarInfoBySaleQuartz(companyId);
    }

    /**
     * @return
     * @throws Exception
     * @desc 批量导入确认
     * @author 术洪超
     */

    @Override
    public void impConfirms(List<Map<Object, String>> data, String uid) throws Exception {
        String companyId=TokenUtil.getCompanyId(uid);
        String sql1 = "select * from " + tabName + " where vin = ? and company_id = ? limit 1";
        List<Object> idList = new ArrayList();
        String tempId;
        Map existData;
        TCrmCarSale crmCarSale;
        for (Map car : data) {
            //查询源数据实体
            tempId = car.get("id").toString();
            crmCarSale = (TCrmCarSale) this.iImpHibernateDao.findEntity(TCrmCarSale.class, tempId);
            existData = this.iJdbcDao.queryForMapBySqlWithParams(sql1, crmCarSale.getVin(), crmCarSale.getCompanyId());
            //源数据主键
            idList.add(tempId);
            //判断数据是否已存在
            if (existData.size() == 0) {
                //新数据
                crmCarSale.setId(null);
                crmCarSale.setCreateTime(System.currentTimeMillis());
                crmCarSale.setUpdateTime(System.currentTimeMillis());
                crmCarSale.setConfirmer(uid);
                crmCarSale.setConfirmDate(System.currentTimeMillis());
            } else {
                //已有数据
                crmCarSale.setId(existData.get("id").toString());
                crmCarSale.setUpdateTime(System.currentTimeMillis());
                crmCarSale.setConfirmer(uid);
                crmCarSale.setConfirmDate(System.currentTimeMillis());
            }
            //保存或更新
            this.iHibernateDao.saveOrUpdateEntity(crmCarSale);
            this.saveOrupdInsuranceCar(crmCarSale,existData);
        }
        //满1000时，删除数据
        this.iImpJdbcDao.batchDel(tabName, "id", idList);

        idList.clear();
        this.itCrmTimeTaskService.updFromCompanyQuartz();
        this.itCrmTimeTaskService.createCrmCarInfoBySaleQuartz(companyId);
    }

    /**
     * @return
     * @throws Exception
     * @desc 导入确认全部
     * @author 术洪超
     */
    @Override
    public void impConfirmAll(String uid) throws Exception {
        /***
         *
         * 车辆更新
         *
         * ***/


        //获取公司 ID
        String companyId = TokenUtil.getCompanyId(uid);
        //编写查询源数据 HQL
        String hql = "from TCrmCarSale where companyId = :companyId";
        //设置参数
        Map<String, Object> params = new HashMap();
        params.put("companyId", companyId);
        //查询公司下的全部车辆
        List<TCrmCarSale> tCrmCarSale = iImpHibernateDao.findEntityListByHqlWithParams(hql, params);
        if (tCrmCarSale == null) {
            throw new Exception("无效的数据！");
        }
        //根据vin判断目标数据是否已存在
        String sql1 = "select * from " + tabName + " where vin = ? and company_id = ? limit 1";
        List<Object> idList = new ArrayList();
        String tempId;
        Map existData;
        for (TCrmCarSale sale : tCrmCarSale) {
            existData = this.iJdbcDao.queryForMapBySqlWithParams(sql1, sale.getVin(), sale.getCompanyId());
            //源数据主键
            tempId = sale.getId();
            idList.add(tempId);
            //判断数据是否已存在
            if (existData.size() == 0) {
                //新数据
                sale.setId(null);
                sale.setCreateTime(System.currentTimeMillis());
                sale.setUpdateTime(System.currentTimeMillis());
                sale.setConfirmer(uid);
                sale.setConfirmDate(System.currentTimeMillis());
            } else {
                //已有数据
                sale.setId(existData.get("id").toString());
                sale.setUpdateTime(System.currentTimeMillis());
                sale.setConfirmer(uid);
                sale.setConfirmDate(System.currentTimeMillis());
            }
            //保存或更新
            this.iHibernateDao.saveOrUpdateEntity(sale);
            this.saveOrupdInsuranceCar(sale,existData);
            //满1000时，删除数据
            if (idList.size() == 1000) {
                this.iImpJdbcDao.batchDel(tabName, "id", idList);
                idList.clear();
            }
        }
        //删除遗留数据
        if (idList.size() > 0) {
            this.iImpJdbcDao.batchDel(tabName, "id", idList);
            idList.clear();
        }
        //由销售数据修正车主车辆的是否本店销属性
        this.itCrmTimeTaskService.updFromCompanyQuartz();
        //由销售数据更新车主车辆档案
        this.itCrmTimeTaskService.createCrmCarInfoBySaleQuartz(companyId);

//        //根据id查询销售实体
//        //String sql = "select * from " + tabName + " where id = ? ";
//        List<TCrmCarSale> tCrmCarSales = iImpHibernateDao.findEntityList(TCrmCarSale.class);
//        if (tCrmCarSales == null) {
//            throw new Exception("无效的数据！");
//        }
//
//        for (TCrmCarSale sale : tCrmCarSales) {
//            //取得vin
//            //String impVin = sale.getVin();
//            //根据vin判断主表立是否已存在
//            //System.out.println(sale.getId());
//            String sql1 = "select * from " + tabName + " where vin = ? and company_id = ? ";
//            Map existData = this.iJdbcDao.queryForMapBySqlWithParams(sql1, sale.getVin(), sale.getCompanyId());
//
//            if (existData.size() == 0) {
//
//                String tempId = sale.getId();
//                sale.setId(null);
//                this.iHibernateDao.saveEntity(sale);
//                this.impDel(tempId);
//            }
//
//
//        }

    }

    private void saveOrupdInsuranceCar(TCrmCarSale sale,Map existData) throws Exception {
        StringBuffer sql=new StringBuffer();
        List<Object> params=new ArrayList<>();
        List list=this.iJdbcDao.queryForMapListBySqlWithParams("select * from t_insurance_car where vin=? and company_id=?",sale.getVin(),sale.getCompanyId());;
        if (list.size() == 0) {

            //插入
            sql.append("insert into t_insurance_car (id, create_time, create_user, insured, insured_address, insured_ID_number, " +
                    "car_model, car_property, car_series,  company_id, contact_name, contact_phone, driver_license, " +
                    "first_record_date,  plate_num, sales_property, vin, saler) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
            params.add(sale.getId());
            params.add(sale.getCreateTime());
            params.add(sale.getCreateUser());
            this.setInsuranceCarParams(params,sale);
        } else {
            sql.append(" update t_insurance_car set insured=?, insured_address=?, insured_ID_number=?," +
                    "car_model=?, car_property=?, car_series=?,  company_id=?, contact_name=?, contact_phone=?, driver_license=?," +
                    "first_record_date=?,  plate_num=?, sales_property=?, vin=?, saler=? where vin=?");
            this.setInsuranceCarParams(params,sale);
            params.add(sale.getVin());
        }
        this.itCrmCarSaleDao.executeSQL(sql.toString(),params.toArray());
    }

    private void setInsuranceCarParams(List<Object> params,TCrmCarSale sale) throws Exception {
        params.add(sale.getOwnerName());
        params.add(sale.getAddress());
        params.add(sale.getOwnerIdentity());
        params.add(sale.getModel());
        if(!"".equals(StringUtil.formatEmpty(sale.getCarProperty()))) {
            if (sale.getCarProperty().indexOf("一次性付款") != -1) {
                params.add("xcqk");
            } else {
                params.add("xcjr");
            }
        }else{
            params.add("");
        }
        params.add(sale.getSeries());
        params.add(sale.getCompanyId());
        params.add(sale.getOwnerName());
        params.add(sale.getOwnerPhone());
        params.add(sale.getOwnerName());
        if(sale.getBuyDate()!=null) {
            params.add(DateUtils.formatLongTimeByYYYYMMDD(sale.getBuyDate()));
        }else{
            params.add("");
        }
        params.add(sale.getPlateNum());
        if(!"".equals(StringUtil.formatEmpty(sale.getSalesProperty()))) {
            if (sale.getSalesProperty().indexOf("本地") != -1) {
                params.add("bdx");
            } else {
                params.add("wdx");
            }
        }else{
            params.add("");
        }
        params.add(sale.getVin());
        params.add(sale.getSaler());
    }

    /**
     * @return
     * @throws Exception
     * @desc 删除全部待导入数据
     * @author 术洪超
     */
    @Override
    public void impDelAll(String uid) throws Exception {

        Map map = new HashMap();
        String companyId = TokenUtil.getCompanyId(uid);
        String hql = " delete from TCrmCarSale where companyId =:companyId";
        map.put("companyId",companyId);
        //System.out.println(companyId);

        this.iImpHibernateDao.executeHqlWithParams(hql, map);
    }

    @Override
    public void impDels(List<Map<Object, String>> data, String uid) throws Exception {
        List<Object> idList = new ArrayList();
        for (Map map : data){
        idList.add(map.get("id"));
    }
        this.iImpJdbcDao.batchDel(tabName,"id",idList);
}
    /**
     * @Name: 销售数据查询
     * @Author: Liu XiaoLong
     * @Date: 2017/9/15 14:36
     * @Remark:
     */
    @Override
    public Map CarSalesDataQuery(String uid, String start, String limit, Map data) throws Exception {

            List params = new ArrayList();
            String sql = "SELECT vin,buy_date buyDate,plate_num plateNum,model,series,owner_name ownerName,owner_phone ownerPhone,address " +
                    "FROM t_crm_car_sale WHERE company_id = ? ";
        if(!StringUtils.isEmpty(data.get("companyId"))){
            params.add(data.get("companyId"));
        }
        else {
            params.add(TokenUtil.getCompanyId(uid));
        }

            if(!StringUtils.isEmpty(data.get("start"))){
                //sql = sql + "AND buy_date >= ? ";
                sql = sql + " AND FROM_UNIXTIME(buy_date/1000, '%Y-%m-%d') >=  ? ";
                //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                //Date date = simpleDateFormat.parse((String) data.get("start"));
                //long ts = date.getTime();
                params.add(data.get("start"));
            }
            if(!StringUtils.isEmpty(data.get("stop"))){
                //sql = sql + "AND buy_date <= ? ";
                sql = sql + "AND FROM_UNIXTIME(buy_date/1000, '%Y-%m-%d') <= ? ";
                //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                //Date date = simpleDateFormat.parse((String) data.get("stop"));
               // long ts = date.getTime();
                params.add(data.get("stop"));
            }
            return iJdbcDao.queryForPageMap(start,limit,sql,params.toArray());

    }


}
